package com.gitee.wsl.platform.thread.lock


import java.util.concurrent.locks.ReentrantReadWriteLock

internal data class JvmSharedMutexHandle(
    val value: ReentrantReadWriteLock
) : SharedMutexHandle

internal actual fun createSharedMutex(): SharedMutexHandle = JvmSharedMutexHandle(ReentrantReadWriteLock())

internal actual fun lockSharedMutex(handle: SharedMutexHandle) {
    require(handle is JvmSharedMutexHandle)
    handle.value.readLock().lock()
}

internal actual fun tryLockSharedMutex(handle: SharedMutexHandle): Boolean {
    require(handle is JvmSharedMutexHandle)
    return handle.value.readLock().tryLock()
}

internal actual fun unlockSharedMutex(handle: SharedMutexHandle) {
    require(handle is JvmSharedMutexHandle)
    handle.value.readLock().unlock()
}

internal actual fun lockWriteSharedMutex(handle: SharedMutexHandle) {
    require(handle is JvmSharedMutexHandle)
    handle.value.writeLock().lock()
}

internal actual fun tryLockWriteSharedMutex(handle: SharedMutexHandle): Boolean {
    require(handle is JvmSharedMutexHandle)
    return handle.value.writeLock().tryLock()
}

internal actual fun unlockWriteSharedMutex(handle: SharedMutexHandle) {
    require(handle is JvmSharedMutexHandle)
    handle.value.writeLock().unlock()
}